<script lang="ts" setup>
import { onMounted, reactive, ref } from "vue";
import { ElMessage, ElMessageBox } from "element-plus";
import * as $accountApi from "@/api/sci/account";

defineOptions({
  name: "account"
});

onMounted(() => {
  _loadData();
});
const drawer = reactive({
  switch: false,
  title: "",
  isUpdate: false
});
const initformData = {
  title: "",
  bonus: "",
  point: "",
  parentId: "",
  rank: 1,
  type: ""
};
const formData = reactive({ ...initformData });
function resetForm() {
  Object.assign(formData, { ...initformData });
}
interface OriginalNode {
  id: string;
  parentId: string | null;
  title: string;
  point: string | null;
  bonus: string | null;
  rank: string;
  type: string;
  modified: string;
  children: OriginalNode[]; // 递归的子节点
}

// 简化后的树形结构类型
interface treeNode {
  label: string;
  value: string;
  point: string;
  bonus: string;
  children: treeNode[]; // 递归的子节点
}
// 当前选中的节点数据
const selectedNode = ref<treeNode | null>(null);
const transformData = (data: any[]): any[] => {
  return data.map(item => ({
    label: item.title,
    value: item.id,
    point: item.point,
    bonus: item.bonus,
    children:
      item.children && item.children.length > 0
        ? transformData(item.children)
        : []
  }));
};
const handleNodeChange = (value: string) => {
  selectedNode.value = findNodeById(drawerTree.value, value);
  formData.bonus = selectedNode.value.bonus;
  formData.point = selectedNode.value.point;
};

// 根据ID查找节点
const findNodeById = (nodes: any[], id: string): any | null => {
  for (const node of nodes) {
    if (node.value === id) {
      return node; // 找到节点
    }
    if (node.children && node.children.length > 0) {
      const result = findNodeById(node.children, id);
      if (result) return result; // 递归查找子节点
    }
  }
  return null; // 如果没有找到
};
function findTypeById(data: OriginalNode[], id: string): string | null {
  for (const node of data) {
    if (node.id === id) {
      return node.type; // 找到匹配的 id，返回对应的 type
    }
    // 如果当前节点没有匹配，递归查找其子节点
    if (node.children.length > 0) {
      const foundType = findTypeById(node.children, id);
      if (foundType) {
        return foundType; // 如果在子节点中找到了，返回对应的 type
      }
    }
  }
  // 如果没有找到匹配的 id，返回 null
  return null;
}
const drawerTree = ref();
const resData = ref();
const _loadData = () => {
  $accountApi
    .treeListAll()
    .then((res: any) => {
      if (res.success) {
        resData.value = res.result;
        drawerTree.value = transformData(res.result);
      }
    })
    .finally(() => {});
};
const _save = () => {
  $accountApi
    .save(formData)
    .then((res: any) => {
      if (res.success) {
        ElMessage({
          message: "添加成功",
          type: "success"
        });
      }
    })
    .catch(error => {
      ElMessage({
        message: error.message || "添加失败，请检查网络或稍后再试。",
        type: "error"
      });
    })
    .finally(() => {
      drawer.switch = false;
      _loadData();
    });
};
const _del = row => {
  $accountApi
    .del(row.id)
    .then((res: any) => {
      if (res.success) {
        ElMessage({
          message: "删除成功",
          type: "success"
        });
      }
    })
    .catch(error => {
      ElMessage({
        message: error.message || "删除失败，请检查网络或稍后再试。",
        type: "error"
      });
    })
    .finally(() => {
      drawer.switch = false;
      _loadData();
    });
};
const _update = () => {
  $accountApi
    .update(formData)
    .then((res: any) => {
      if (res.success) {
        ElMessage({
          message: "更新成功",
          type: "success"
        });
      }
    })
    .finally(() => {
      drawer.switch = false;
      _loadData();
    });
};
const saveOrUpdate = () => {
  if (formData.parentId !== "") {
    formData.type = findTypeById(resData.value, formData.parentId);
    drawer.isUpdate ? _update() : _save();
  } else {
    openDialog();
  }
};
const openDialog = () => {
  ElMessageBox.prompt("请输入核算类型", "提示", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    inputErrorMessage: "请输入核算类型"
  })
    .then(({ value }) => {
      formData.type = value;
      drawer.isUpdate ? _update() : _save();
    })
    .catch(() => {
      ElMessage({
        type: "info",
        message: "取消"
      });
    });
};
const update = row => {
  drawer.title = "编辑核算";
  drawer.switch = true;
  drawer.isUpdate = true;
  row.rank = Number(row.rank);
  Object.assign(formData, row);
};
const save = () => {
  drawer.title = "新增核算";
  drawer.switch = true;
  drawer.isUpdate = false;
};
const saveByRow = (row: any) => {
  drawer.title = "新增核算";
  drawer.switch = true;
  drawer.isUpdate = false;
  formData.rank = 1;
  formData.parentId = row.id;
};
</script>

<template>
  <el-card :shadow="'never'">
    <el-button type="primary" @click="save()">
      <el-icon style="vertical-align: middle">
        <DocumentAdd />
      </el-icon>
      <span style="vertical-align: middle">新增</span>
    </el-button>
    <div class="table-wrapper" style="margin-top: 20px">
      <el-scrollbar>
        <el-table
          border
          :data="resData"
          stripe
          :header-cell-style="{
            backgroundColor: '#FFFAFA',
            padding: '3px',
            color: 'black'
          }"
          :row-style="{ height: '50px' }"
          :resizable="false"
          row-key="id"
          :tree-props="{ children: 'children' }"
          height="800"
        >
          <el-table-column
            width="800"
            prop="title"
            label="核算名称"
            align="left"
            :resizable="false"
          />
          <el-table-column
            prop="point"
            label="业绩点"
            align="center"
            :resizable="false"
          />
          <el-table-column
            prop="bonus"
            label="科研奖金"
            align="center"
            :resizable="false"
          />
          <el-table-column
            fixed="right"
            label="操作"
            width="300"
            align="center"
          >
            <template #default="scope">
              <el-button
                type="success"
                bg
                size="small"
                @click="update(scope.row)"
                >编辑</el-button
              >
              <el-button
                type="info"
                bg
                size="small"
                @click="saveByRow(scope.row)"
                >新增</el-button
              >
              <el-popconfirm title="确定要删除此项?" @confirm="_del(scope.row)">
                <template #reference>
                  <el-button type="warning" bg size="small">删除</el-button>
                </template>
              </el-popconfirm>
            </template>
          </el-table-column>
        </el-table>
      </el-scrollbar>
    </div>
    <el-drawer v-model="drawer.switch" :title="drawer.title" @close="resetForm">
      <el-form
        :inline="true"
        :model="formData"
        class="demo-form-inline"
        label-width="auto"
      >
        <el-form-item label="核算名称">
          <el-input v-model="formData.title" clearable />
        </el-form-item>
        <el-form-item label="业绩点">
          <el-input v-model="formData.point" clearable />
        </el-form-item>
        <el-form-item label="科研奖金">
          <el-input v-model="formData.bonus" clearable />
        </el-form-item>
        <el-form-item label="显示排序">
          <el-input-number v-model="formData.rank" :min="1" :max="100" />
        </el-form-item>
        <el-form-item label="上级菜单">
          <el-tree-select
            v-model="formData.parentId"
            :data="drawerTree"
            check-strictly
            :render-after-expand="false"
            style="width: 240px"
            @change="handleNodeChange"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="saveOrUpdate()">确定</el-button>
          <el-button type="primary" @click="drawer.switch = false">
            关闭
          </el-button>
        </div>
      </template>
    </el-drawer>
  </el-card>
</template>
<style lang="scss" scoped>
.table-wrapper {
  margin-bottom: 20px;
}
</style>
